package com.hwh.bootdemoweb.Netty第六章;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @author wenhao hu
 * @title: EventLoopClient
 * @projectName bootdemoweb
 * @description: TODO
 * @date 2021/12/1712:01
 */
@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        //2 带有Future、Promise的类型都是同异步方法配套使用
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder()); //将bytebuffer转换成字符串
                    }
                })
                //连接到服务器端
                .connect(new InetSocketAddress(8080));

        //2.2 使用addListener方法异步处理结果
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            //再NIO线程连接建立完成后，会调用这个方法。
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                Channel channel = channelFuture.channel();
                log.debug("{}",channel);
                channel.writeAndFlush("hello");
            }
        });
    }
}
